package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"huiyun/huiyunrpc/huiyunrpc"
	"huiyun/huiyunrpc/internal/svc"
	"huiyun/model/cache"
	"huiyun/model/mysql"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type SportListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSportListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SportListLogic {
	return &SportListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 活动列表
func (l *SportListLogic) SportList(in *huiyunrpc.SportListRequest) (*huiyunrpc.SportListResponse, error) {
	// todo: add your logic here and delete this line
	page := in.Page
	if page <= 0 {
		page = 1
	}

	Size := in.Size
	switch {
	case Size > 100:
		Size = 100
	case Size <= 0:
		Size = 10
	}
	offset := page - 1*Size
	var sport []mysql.Sport
	key := fmt.Sprintf("SportList%d%d", in.Page, in.Size)
	result, _ := cache.Rdb.Get(l.ctx, key).Result()
	if result == "" {
		mysql.DB.Debug().Offset(int(offset)).Limit(int(Size)).Order("created_at desc").Find(&sport)
		marshal, _ := json.Marshal(&sport)
		cache.Rdb.Set(l.ctx, key, marshal, time.Hour*24)

	} else {
		json.Unmarshal([]byte(result), &sport)
	}
	var sportlist []*huiyunrpc.SportList
	for _, m := range sport {
		list := huiyunrpc.SportList{
			Image:     m.Image,
			Name:      m.Name,
			ClassName: m.ClassName,
			Writer:    m.Writer,
			Num:       m.Num,
			UserId:    m.UserId,
		}
		sportlist = append(sportlist, &list)
	}
	return &huiyunrpc.SportListResponse{
		List: sportlist,
	}, nil
}
